package com.muqi.server.common.interceptor;

import com.muqi.server.common.annotated.RequiresPermission;
import com.muqi.server.common.response.ResponseClass;
import com.muqi.server.common.utilis.UserUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.HandlerInterceptor;

import java.lang.reflect.Method;
@Component
@ConditionalOnClass(DispatcherServlet.class)
public class PermissionInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();

            if (method.isAnnotationPresent(RequiresPermission.class)) {
                RequiresPermission annotation = method.getAnnotation(RequiresPermission.class);
                int[] requiredPermissions = annotation.value();

                int userPermissions = UserUtil.getType();
                if (userPermissions == -1) {
                    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    response.setCharacterEncoding("UTF-8"); // 设置字符编码为UTF-8
                    response.setContentType("application/json; charset=utf-8"); // 设置返回的数据类型
                    response.getWriter().write(new ResponseClass(HttpServletResponse.SC_UNAUTHORIZED, null, "未登录").toString());
                    return false; // 返回false表示拦截该请求
                }

                boolean hasPermission = false;

                for (int requiredPermission : requiredPermissions) {
                    if (userPermissions == requiredPermission) {
                        hasPermission = true;
                        break;
                    }
                }

                if (!hasPermission) {
                    response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                    response.setCharacterEncoding("UTF-8"); // 设置字符编码为UTF-8
                    response.setContentType("application/json; charset=utf-8"); // 设置返回的数据类型
                    response.getWriter().write(new ResponseClass(HttpServletResponse.SC_FORBIDDEN, null, "权限不足").toString());
                    return false; // 返回false表示拦截该请求
                }
            }
        }

        return true; // 返回true表示放行该请求
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 在整个请求结束之后被调用，也就是在DispatcherServlet渲染了对应的视图之后执行
    }

}
